<template>
  <div class="login-container">
    <div class="login-center">
      <div class="login-center__header">
        <embed src="../../assets/svg/whiteLogo.svg"
               width="111" height="26"
               type="image/svg+xml"
               pluginspage="http://www.adobe.com/svg/viewer/install/"/>
        <div class="header-register" @click="handleRegister">注册</div>
      </div>

      <login-wrap
        title1="密码登录"
        title2="短信登录"
        @firstWay="handleLoginPassword"
        @secondWay="handleLoginCode"
      >
        <template #mainContent>
          <login-input
            :error-message="accountErrMsg"
            :placeholder="placeholder"
            v-model="account"
            @handleCheck="checkAccount"
            @cancelCheck="accountErrMsg = ''"
            @keyup.enter.native="handleLogin"
          ></login-input>
          <login-input
            :error-message="passwordErrMsg"
            placeholder="请输入密码"
            input-type="2"
            :type="type"
            v-model="password"
            v-if="isPassword"
            @handleCheck="checkPassword"
            @cancelCheck="passwordErrMsg = ''"
            @keyup.enter.native="handleLogin"
            @handleShowPassword="handleShowPassword"
          ></login-input>
          <login-input
            :error-message="verifyErrMsg"
            :isCount="isCount"
            placeholder="请输入验证码"
            input-type="3"
            v-model="verifyCode"
            v-if="!isPassword"
            @sendSms="checkVerification"
            @cancelCheck="verifyErrMsg = ''"
            @keyup.enter.native="handleLogin"
          ></login-input>
        </template>
        <template #mainFooter>
          <login-button @handle="handleLogin" button="登录"></login-button>
        </template>
      </login-wrap>

      <div class="login-footer">
        Copyright © 2019 云里云外开源社区 All Rights Reserved · 京ICP备 1234567891号-11
      </div>
    </div>
  </div>
</template>
<script>
import loginWrap from '../../components/pc/loginCard/loginWrap'
import LoginInput from "../../components/pc/loginCard/loginInput";
import LoginButton from "../../components/pc/loginCard/loginButton";
import config from '../../action/config';
import {checkAccount, checkPhone, checkPassword, checkVerification} from './checkfrom';

const Cookie = process.client ? require('js-cookie') : null;

export default {
  layout: 'blank',
  components: {
    LoginButton,
    LoginInput,
    loginWrap
  },
  data() {
    return {
      type: 'password',     // 显示密码
      account: '',          // 保存 手机号 邮箱
      password: '',         // 保存 密码
      verifyCode: '',       // 保存 验证码
      isPassword: true,     // 判断验证码
      placeholder: '请输入手机号或邮箱',
      accountErrMsg: '',    // 手机号 邮箱 错误提示
      passwordErrMsg: '',   // 密码错误 提示信息
      verifyErrMsg: '',     // 验证码错误 提示信息
      isCount: false,       // 是否开始倒计时
      from:'/'
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.from = from.fullPath
    });
  },

  methods: {
    // 显示为密码登录
    handleLoginPassword() {
      Object.assign(this.$data, this.$options.data());
      this.isPassword = true;
      this.placeholder = '请输入手机号或邮箱';
    },
    // 显示为 验证码登录
    handleLoginCode() {
      Object.assign(this.$data, this.$options.data());
      this.isPassword = false;
      this.placeholder = '请输入手机号';
    },
    // 控制密码显示
    handleShowPassword() {
      this.type = this.type === 'password' ? 'text' : 'password';
    },
    // 跳转注册页面
    handleRegister() {
      this.$router.push('/users/register');
    },
    // 检测account 手机 邮箱
    checkAccount() {
      if (this.isPassword) {
        this.accountErrMsg = checkAccount(this.account) === '' ? '' : '账号格式错误';
      } else {
        this.accountErrMsg = checkPhone(this.account);
      }
    },
    // 检测 密码
    checkPassword() {
      this.passwordErrMsg = checkPassword(this.password, true);
    },
    // 检测验证码
    checkVerification() {
      this.isCount = false;
      this.accountErrMsg = checkPhone(this.account);
      if (this.accountErrMsg === '') {
        this.getSms();
        this.verifyErrMsg = '';
        this.isCount = true;
        setTimeout(() => {
          this.isCount = false;
        }, 60000);
      }
    },
    // 发送短信
    async getSms() {
      let smsResponse = await this.$axios.$get(config.api.get.Sms.send, {
        params: {
          mobile: this.account
        }
      });
      if (smsResponse.code === 0) {
        this.$message({
          type: 'success',
          message: '短信发送成功！'
        });
      } else {
        this.verifyErrMsg = smsResponse.msg;
        this.$message({
          type: 'info',
          message: smsResponse.msg
        });
      }
    },
    // 进行登录
    async handleLogin() {
      // 防止全部未输入就点击
      this.checkAccount();
      this.checkPassword();
      this.verifyErrMsg = checkVerification(this.verifyCode);

      let authResponse;
      // 两种登录方式
      if (this.isPassword && this.passwordErrMsg === '' && this.accountErrMsg === '') {
        authResponse = await this.$axios.$post(config.api.post.Authentication.accountAuth, {
          account: this.account,
          password: this.password
        });
      } else if (!this.isPassword && this.verifyErrMsg === '' && this.accountErrMsg === '') {
        authResponse = await this.$axios.$post(config.api.post.Authentication.smsAuth, {
          mobile: this.account,
          verifyCode: this.verifyCode
        });
      }

      // 认证成功
      if (authResponse !== undefined && authResponse.code === 0) {
        // 获取token
        const token = authResponse.data.accessToken;
        const store = this.$store;

        // 设置认证信息
        store.commit('auth/login', token);

        // 获取用户信息
        const userInfoResponse = await this.$axios.$get(config.api.get.User.myInfo);
        if (userInfoResponse.code === 0) {
          // 存储用户信息
          store.commit('userProfile/setUser', userInfoResponse.data);

          // 若登录和获取用户信息都成功，则存储认证信息到cookie
          Cookie.set(config.default_data.KEY_COOKIE_TOKEN, token);

          // 获取未读消息数量
          const messageResponse = await this.$axios.$get(config.api.get.Message.count);
          store.commit('message/setUnReadCount', messageResponse.data.unReadCount)

          // 跳转到主页
          this.$message({
            type: 'success',
            message: '登录成功！'
          });
          if (!this.from || this.from === '/users/register' || this.from === '/users/reset') {
            this.$router.push('/')
          } else {
            this.$router.push(this.from)
          }
        } else {
          store.commit('auth/logout');
          store.commit('userProfile/removeUser')
        }
      } else if (authResponse !== undefined) {
        // 认证失败
        // errorCode(authResponse);
        if (authResponse.code === 1002) {
          this.passwordErrMsg = authResponse.msg;
        } else if (authResponse.code === 1001) {
          this.accountErrMsg = authResponse.msg;
        }else if (authResponse.code === 1003) {
          this.verifyErrMsg = authResponse.msg;
        } else {
          this.$message({
            type: 'error',
            message: authResponse.msg
          });
        }
      }
    }

  }
}
</script>

<style lang="scss" scoped>
  .login-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-image: url("../../assets/img/background.png");
    background-repeat: no-repeat;
    background-size: cover;

    .login-center {
      width: $pageWidth;
      height: 100%;
      margin: 0 auto;
      @extend %flex-column-spb;

      .login-center__header {
        width: 100%;
        margin-top: 20*$length;
        @extend %flex-row-spb;
        @include fontStyle(14, 20, 500, #fff, left);

        .header-register {
          @extend %cursorPointer;
        }
      }

      .login-footer {
        margin-bottom: 30*$length;
        @include fontStyle(12, 17, 500, #fff, center);
        cursor: default;
      }
    }
  }
</style>
